<?php

@session_start();

/**
 * @author JLQ
 * @copyright 2009 JLQ
 */
require './dbconfig.php';
require './administration/Libraries/Tools/JLTools.class.php';
require './administration/Libraries/JLAjax.class.php';

$name = filter_var($_POST['txtnom'], FILTER_SANITIZE_STRING);
$email = strtolower(filter_var($_POST['txtemail'], FILTER_SANITIZE_STRING));

$Ajax = JLAjax::getInstance();
$Ajax->checkToken();

if ($Ajax->isAjaxRequest()) {
    if ($Ajax->isValidToken() && !empty($name) && !empty($email)) {
//        $Ajax->resetToken();

        $jl = new JLTools();
        $var_code = $jl->RandomNumerosLetras(78, "ambos");
        $query = "SELECT `var_email` FROM `tbl_suscriptores` 
        WHERE `var_email` = '$email'
        LIMIT 1";
        $res = mysql_query($query, $cnn);

        if (mysql_affected_rows($cnn) > 0) {
            $Ajax->response(RESPONSE_CODE_ALERT);
        }

        if (sendEmail($name, $email)) {
            $query = "INSERT INTO 
              `tbl_suscriptores`(
              `var_fullname`,
              `var_email`,
              `var_code`
            ) VALUE(
              '$name',
              '$email',
              '$var_code'
            )";
            $res = mysql_query($query, $cnn);
        }

//        if (mysql_affected_rows($cnn) > 0) {
        $Ajax->resetToken();
        $Ajax->response(RESPONSE_CODE_OK);
//        } else {
//            $Ajax->response(RESPONSE_CODE_ERROR, "Désolé, il n'ya pas actuellement en mesure de vous aider, réessayez plus tard.");
//        }
    } else {
        $Ajax->forbiddenHeader();
    }
} else {
    header("Location: ./");
    exit;
}

function sqlQuote($value, $cnn) {
    if (get_magic_quotes_gpc())
        $value = stripslashes($value);
    if (function_exists("mysql_real_escape_string"))
        $value = mysql_real_escape_string($value, $cnn);
    else
        $value = addslashes($value);
    return $value;
}

function sendEmail($name, $email) {
    require "./administration/Libraries/Tools/phpmailer/phpmailer.php";
    $mail = new PHPMailer();

    $mail->PluginDir = "";
    $mail->IsHTML(true);
    $mail->CharSet = "utf-8";
    $mail->IsMail();
    $mail->Timeout = 10;
    $mail->From = "system@csme.fr";
    $mail->FromName = utf8_encode("CSME");
    $mail->Subject = 'Inscription Newsletter CSME';
    $mail->AddAddress($name . " <" . $email . ">");
    $server_path = getNameDomain();
    $message = str_replace("%SERVER%", $server_path, file_get_contents('images/mail/note_inscrit.html'));
    $mail->Body = $message;

    return $mail->Send();
}

function checkDomain($email) {
//    $domain = preg_replace('/^.+?@/', '', $email) . '.';
    list($user, $domain) = split('@', $email);
    return filter_var($email, FILTER_VALIDATE_EMAIL) && checkdnsrr($domain, 'MX') && checkdnsrr($domain, 'A');
}

//function domain_exists($email, $record = 'MX') {
//    list($user, $domain) = split('@', $email);
//    return checkdnsrr($domain, $record);
//}